/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.dynamicform.core.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.lcm.metadata.spi.event.MetadataEventArgs;
import com.inspur.edp.web.common.entity.ResultCode;
import com.inspur.edp.web.common.entity.ResultMessage;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.metadata.MetadataGetterParameter;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.DateUtility;
import com.inspur.edp.web.common.utility.RandomUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.designschema.elements.Field;
import com.inspur.edp.web.designschema.elements.Schema;
import com.inspur.edp.web.designschema.elements.SimpleField;
import com.inspur.edp.web.designschema.generator.SchemaBuilder;
import com.inspur.edp.web.dynamicform.core.api.customexception.DynamicFormException;
import com.inspur.edp.web.dynamicform.core.api.entity.*;
import com.inspur.edp.web.dynamicform.core.api.service.DynamicCreateFormMetadataService;
import com.inspur.edp.web.dynamicform.core.components.CardTemplateEditorGenerator;
import com.inspur.edp.web.dynamicform.core.components.ComponentBinding;
import com.inspur.edp.web.dynamicform.core.components.GridFieldComponentMetadata;
import com.inspur.edp.web.dynamicform.core.components.QuerySchemaField;
import com.inspur.edp.web.dynamicform.core.statemachine.StateMachineMetadataGenerator;
import com.inspur.edp.web.formmetadata.metadata.FormMetadataContent;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormOptions;
import com.inspur.edp.web.pageflow.metadata.service.PageFlowMetadataUpdateService;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 动态创建表单
 *
 * @author guozhiqi
 */
public class DynamicCreateFormMetadataServiceImpl implements DynamicCreateFormMetadataService {
    @Override
    public ResultMessage<String> create(DynamicCreateFormMetadataParameter parameter) {
        // 入参校验 主要针对需要必须填写的内容进行验证
        this.createParameterValidate(parameter);

        ResultMessage resultMessage = ResultCode.success();


        String formMetadataRelativePath = FileUtility.getPlatformIndependentPath(FileUtility.combine(parameter.getProjectPath(), "components"));
        // 此处应该可能存在同时多个表单创建的情况  此处先使用第一个
        if (!parameter.getFormMetadataInfoList().isEmpty()) {
            for (FormMetadataInfo metadataInfoItem : parameter.getFormMetadataInfoList()) {
                GspMetadata formListMetadata = new GspMetadata();
                formListMetadata.setRelativePath(formMetadataRelativePath);
                MetadataHeader metadataHeader = new MetadataHeader();
                metadataHeader.setName(metadataInfoItem.getName());
                metadataHeader.setCode(metadataInfoItem.getCode());
                metadataHeader.setFileName(metadataInfoItem.getCode() + ".frm");
                metadataHeader.setId(RandomUtility.newGuid());
                metadataHeader.setNameSpace(parameter.getProjectNameSpace());
                metadataHeader.setBizobjectID(parameter.getBizobjectID());
                metadataHeader.setType("Form");

                formListMetadata.setHeader(metadataHeader);

                // 读取资源文件中模板信息
                FormMetadataTemplateInfo formMetadataTemplateInfo = metadataInfoItem.getTemplateInfo();
                String templateFilePath = FileUtility.getPlatformIndependentPath(FileUtility.combine(FileUtility.getCurrentWorkPath(false), "web\\platform\\dev\\main\\web\\webide\\plugins\\form-create-wizard\\assets\\templates\\form-template\\" + formMetadataTemplateInfo.getTemplateId() + ".json"));
                String templateContent = FileUtility.readAsString(templateFilePath);

                FormMetadataContent formMetadataContent = new FormMetadataContent();
                formMetadataContent.setId(metadataHeader.getId());
                formMetadataContent.setCode(metadataInfoItem.getCode());
                formMetadataContent.setName(metadataInfoItem.getName());
                formMetadataContent.setCreationDate(DateUtility.convertFromLocalDateTime(LocalDateTime.now()));

                FormDOM formDOM = SerializeUtility.getInstance().deserialize(templateContent, FormDOM.class);
                // 读取VO元数据  进行表单参数构造
                MetadataGetterParameter metadataGetterParameter = MetadataGetterParameter.getNewInstance(metadataInfoItem.getVoMetadataId(), FileUtility.getPlatformIndependentPath(parameter.getProjectPath()), MetadataTypeEnum.ViewModel);
                GspMetadata voMetadata = MetadataUtility.getInstance().getMetadataWithDesign(metadataGetterParameter);
                IMetadataContent voMetaContent = voMetadata.getContent();
                GspViewModel gspViewModel = (GspViewModel) voMetaContent;
                SchemaBuilder schemaBuilder = new SchemaBuilder();
                Schema schema = schemaBuilder.buildWithScene(gspViewModel, "", false);
                schema.setId(voMetadata.getHeader().getId());
                schema.setCode(metadataInfoItem.getCode());
                schema.setEapiId(metadataInfoItem.getEapiMetadataId());
                schema.setEapiCode(metadataInfoItem.getEapiMetadataCode());
                schema.setEapiName(metadataInfoItem.getEapiMetadataName());

                // 设置对应eapi的sourceUri
                // 如果未传递对应的sourceUri  那么使用当前表单进行自定义uri
                if (StringUtility.isNullOrEmpty(metadataInfoItem.getEapiSourceUri())) {
                    String[] relativePathArr = formMetadataRelativePath.split("/");
                    String strSourceUri = ("/api/" + relativePathArr[0] + "/" + relativePathArr[1] + "/v1.0/" + metadataInfoItem.getCode()).toLowerCase();
                    schema.setSourceUri(strSourceUri);
                } else {
                    schema.setSourceUri(metadataInfoItem.getEapiSourceUri());
                }

                List<Schema> schemaList = new ArrayList<Schema>() {{
                    this.add(schema);
                }};

                String serializedSchema = SerializeUtility.getInstance().serialize(schemaList);
                ArrayList<HashMap<String, Object>> deserializedSchema = SerializeUtility.getInstance().deserialize(serializedSchema, ArrayList.class);
                formDOM.getModule().setSchemas(deserializedSchema);

                formDOM.getModule().setId(metadataInfoItem.getCode());
                formDOM.getModule().setCode(metadataInfoItem.getCode());
                formDOM.getModule().setName(metadataInfoItem.getName());
                formDOM.getModule().setCreator("Noah");
                formDOM.getModule().setCreationDate(DateUtility.getCurrentDateTime());
                formDOM.getModule().setCaption(metadataInfoItem.getName());
                formDOM.getModule().setType("Module");
                formDOM.getModule().setShowTitle(true);
                formDOM.getModule().setBootstrap(metadataInfoItem.getTemplateInfo().getTemplateId());
                formDOM.getModule().setTemplateId(metadataInfoItem.getTemplateInfo().getTemplateId());

                // 设置扩展信息
                formDOM.setOptions(new FormOptions() {
                    {
                        this.setEnableTextArea(true);
                        this.setRenderMode("compile");
                    }
                });

                // 状态机元数据保存
                StateMachineMetadataGenerator.saveStateMachineAndRefreshForm(parameter, formMetadataRelativePath, metadataInfoItem, formListMetadata, formDOM);


                if (formDOM.getModule().getComponents() != null) {

                    formDOM.getModule().getComponents().forEach(componentItem -> {
                        if (Objects.equals(componentItem.get("id"), "root-component")) {
                            if (metadataInfoItem.getTemplateInfo().isListTemplate()) {
                                componentItem.put("onInit", "Filter1");
                            } else if (metadataInfoItem.getTemplateInfo().isNewCardTemplate()) {
                                componentItem.put("onInit", "Load1");
                            }
                        }

                        // 当前的componentId
                        String currentComponentId = componentItem.get("id").toString();

                        this.rescureHashMapWithContents(componentItem, (childItem) -> {
                            if (Objects.equals(childItem.get("id"), "header-title-container") && childItem.get("contents") instanceof ArrayList) {
                                ArrayList<HashMap<String, Object>> headerTitleContainerContents = (ArrayList<HashMap<String, Object>>) childItem.get("contents");
                                headerTitleContainerContents.forEach(headerItem -> {
                                    if (Objects.equals(headerItem.get("type"), "HtmlTemplate")) {
                                        String strHeaderHtml = headerItem.get("html").toString();
                                        strHeaderHtml = strHeaderHtml.replace("${title}", metadataInfoItem.getName());
                                        // 移除模板中的${formCode} 无效字符串
                                        strHeaderHtml = strHeaderHtml.replace("${formCode}", "");
                                        headerItem.put("html", strHeaderHtml);
                                    }
                                });
                            }

                            if (metadataInfoItem.getTemplateInfo().isListTemplate() &&
                                    Objects.equals(childItem.get("id"), "dataGrid")) {
                                // 选中对应的列表
                                childItem.computeIfPresent("fields", (k, v) -> new ArrayList<>());

                                // 仅限于单列表处理 向列表添加属性参数
                                schema.getEntities().stream().findFirst().ifPresent(mainEntity -> {
                                    List<Field> fieldList = mainEntity.getType().getFields();
                                    fieldList.forEach(fieldItem -> {
                                        HashMap<String, Object> defaultGridMetadatMetadata = GridFieldComponentMetadata.getDefaultGridFieldMetadata();

                                        String generatedMetadataId = fieldItem.getId().length() > 8 ? fieldItem.getId().substring(0, 8) : fieldItem.getId();
                                        generatedMetadataId = fieldItem.getBindingField() + "_" + generatedMetadataId.replaceAll("-", "_") + "_" + RandomUtility.newGuid(4);
                                        defaultGridMetadatMetadata.put("id", generatedMetadataId);

                                        defaultGridMetadatMetadata.put("caption", fieldItem.getName());
                                        defaultGridMetadatMetadata.put("dataField", fieldItem.getLabel());

                                        ComponentBinding componentBinding = new ComponentBinding() {{
                                            this.setType("Form");
                                            this.setPath(fieldItem.getBindingField());
                                            this.setField(fieldItem.getId());
                                            this.setFullPath(fieldItem.getPath());

                                        }};
                                        defaultGridMetadatMetadata.put("binding", componentBinding);

                                        ((ArrayList) childItem.get("fields")).add(defaultGridMetadatMetadata);
                                    });
                                });

                                Optional dataGridViewModelOpt = formDOM.getModule().getviewmodels().stream().filter(t ->
                                        Objects.equals(t.get("id"), "data-grid-component-viewmodel")).findFirst();
                                dataGridViewModelOpt.ifPresent(dataGridViewModelItem -> {
                                    HashMap<String, Object> hashMapViewModelItem = (HashMap<String, Object>) dataGridViewModelItem;
                                    ((HashMap<String, Object>) dataGridViewModelItem).put("bindTo", "/");
                                    List<HashMap<String, Object>> viewModelFieldList = new ArrayList<>();
                                    schema.getEntities().stream().findFirst().ifPresent(t -> {
                                        t.getType().getFields().forEach(schemaFieldItem -> {
                                            HashMap<String, Object> hashMapSchemaField = new HashMap<>();
                                            hashMapSchemaField.put("type", "Form");
                                            hashMapSchemaField.put("id", schemaFieldItem.getId());
                                            hashMapSchemaField.put("fieldName", schemaFieldItem.getBindingField());
                                            hashMapSchemaField.put("groupId", null);
                                            hashMapSchemaField.put("groupName", null);
                                            viewModelFieldList.add(hashMapSchemaField);
                                        });
                                    });

                                    hashMapViewModelItem.put("fields", viewModelFieldList);
                                });
                            }


                            if (metadataInfoItem.getTemplateInfo().isNewCardTemplate()) {
                                Optional basicFormViewModelOpt = formDOM.getModule().getviewmodels().stream().filter(t ->
                                        Objects.equals(t.get("id"), "basic-form-viewmodel")).findFirst();
                                basicFormViewModelOpt.ifPresent(basicFormViewModelItem -> {
                                    HashMap<String, Object> hashMapViewModelItem = (HashMap<String, Object>) basicFormViewModelItem;
                                    ((HashMap<String, Object>) basicFormViewModelItem).put("bindTo", "/");
                                    List<HashMap<String, Object>> viewModelFieldList = new ArrayList<>();
                                    schema.getEntities().stream().findFirst().ifPresent(t -> {
                                        t.getType().getFields().forEach(schemaFieldItem -> {
                                            HashMap<String, Object> hashMapSchemaField = new HashMap<>();
                                            hashMapSchemaField.put("type", "Form");
                                            hashMapSchemaField.put("id", schemaFieldItem.getId());
                                            hashMapSchemaField.put("fieldName", schemaFieldItem.getBindingField());
                                            hashMapSchemaField.put("groupId", null);
                                            hashMapSchemaField.put("groupName", null);
                                            viewModelFieldList.add(hashMapSchemaField);
                                        });
                                    });

                                    hashMapViewModelItem.put("fields", viewModelFieldList);
                                });
                            }

                            if (metadataInfoItem.getTemplateInfo().isListTemplate() && Objects.equals(childItem.get("id"), "query-scheme-section")) {
                                ArrayList<HashMap<String, Object>> querySchemaSectionContents = (ArrayList<HashMap<String, Object>>) childItem.get("contents");
                                querySchemaSectionContents.forEach(contentItem -> {
                                    if (Objects.equals(contentItem.get("type"), "QueryScheme")) {
                                        contentItem.put("formId", metadataInfoItem.getCode());

                                        contentItem.put("presetQuerySolutionName", "默认筛选方案");
                                        // 构造筛选方案fields
                                        List<Field> schemaEntityFieldList = schema.getEntities().stream().findFirst().get().getType().getFields();
                                        List<QuerySchemaField> querySchemaFieldList = schemaEntityFieldList.stream().map(fieldItem -> {
                                            QuerySchemaField querySchemaField = new QuerySchemaField();
                                            querySchemaField.setId(fieldItem.getId());
                                            querySchemaField.setCode(fieldItem.getCode());
                                            querySchemaField.setName(fieldItem.getName());
                                            querySchemaField.setLabelCode(fieldItem.getPath());

                                            String fieldEditorType = ((SimpleField) fieldItem).getEditor().get$type();
                                            QuerySchemaField.QuerySchemaFieldControl querySchemaFieldControl = null;
                                            boolean hasFieldControl = true;
                                            switch (fieldEditorType) {
                                                case "TextBox":
                                                    querySchemaFieldControl = new QuerySchemaField.QuerySchemaTextFieldControl();
                                                    break;
                                                case "NumericBox":
                                                    QuerySchemaField.QuerySchemaNumberFieldControl querySchemaNumberFieldControl = new QuerySchemaField.QuerySchemaNumberFieldControl();
                                                    querySchemaNumberFieldControl.setId(fieldItem.getId());
                                                    querySchemaNumberFieldControl.setPrecision(0d);
                                                    querySchemaNumberFieldControl.setBigNumber(fieldItem.getType().getName().equals("BigNumber"));
                                                    querySchemaFieldControl = querySchemaNumberFieldControl;
                                                    break;
                                                case "DateBox":
                                                    QuerySchemaField.QuerySchemaDateFieldControl querySchemaDateFieldControl = new QuerySchemaField.QuerySchemaDateFieldControl();
                                                    querySchemaDateFieldControl.setId(fieldItem.getId());
                                                    querySchemaFieldControl = querySchemaDateFieldControl;
                                                    break;
                                                case "EnumField":
                                                    QuerySchemaField.QuerySchemaDropdownFieldControl querySchemaDropdownFieldControl = new QuerySchemaField.QuerySchemaDropdownFieldControl();
                                                    querySchemaDropdownFieldControl.setId(fieldItem.getId());
                                                    querySchemaDropdownFieldControl.setValueType("1");
                                                    //querySchemaDropdownFieldControl.setEnumValues(fieldItem.getType().get);
                                                    querySchemaFieldControl = querySchemaDropdownFieldControl;
                                                    break;
                                                case "CheckBox":
                                                    QuerySchemaField.QuerySchemaDropdownFieldControl querySchemaDropdownFieldControlWithCheckBox = new QuerySchemaField.QuerySchemaDropdownFieldControl();
                                                    querySchemaDropdownFieldControlWithCheckBox.setId(fieldItem.getId());
                                                    querySchemaDropdownFieldControlWithCheckBox.setValueType("2");

                                                    ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode(2);
                                                    ObjectNode trueNode = JsonNodeFactory.instance.objectNode();
                                                    trueNode.put("value", true);
                                                    trueNode.put("name", "true");
                                                    arrayNode.add(trueNode);

                                                    ObjectNode falseNode = JsonNodeFactory.instance.objectNode();
                                                    falseNode.put("value", false);
                                                    falseNode.put("name", "false");
                                                    arrayNode.add(falseNode);
                                                    querySchemaDropdownFieldControlWithCheckBox.setEnumValues(arrayNode);
                                                    querySchemaFieldControl = querySchemaDropdownFieldControlWithCheckBox;
                                                    break;
                                                default:
                                                    hasFieldControl = false;
                                                    WebLogger.Instance.info("筛选方案字段构造，未匹配到合适的Editor 类型，使用默认的text类型");
                                                    break;
                                            }
                                            if (hasFieldControl) {
                                                querySchemaFieldControl.setId(fieldItem.getId());
                                                querySchemaFieldControl.setRequire(false);

                                                Optional<FormFieldInfo> optionalFieldInfo = metadataInfoItem.getFormFilterInfo().getFieldInfoList().stream().filter(t -> t.getCode().equals(querySchemaField.getCode())).findFirst();

                                                QuerySchemaField.QuerySchemaFieldControl finalQuerySchemaFieldControl = querySchemaFieldControl;
                                                if (optionalFieldInfo.isPresent()) {

                                                    // 如果传递了是否可见属性参数值  那么使用
                                                    finalQuerySchemaFieldControl.setRequire(optionalFieldInfo.get().isRequired());
                                                    if (optionalFieldInfo.get().isShow()) {
                                                        querySchemaField.setControl(querySchemaFieldControl);
                                                    }
                                                } else {
                                                    querySchemaField.setControl(querySchemaFieldControl);
                                                }


                                                return querySchemaField;
                                            }
                                            return null;
                                        }).filter(Objects::nonNull).collect(Collectors.toList());
                                        contentItem.put("fieldConfigs", querySchemaFieldList);
                                        contentItem.put("presetFieldConfigs", querySchemaFieldList);
                                    }
                                });
                            }

                            // 卡片模板
                            // 查找对应的Form
                            if (metadataInfoItem.getTemplateInfo().isNewCardTemplate() && Objects.equals(currentComponentId, "basic-form-component") && Objects.equals(childItem.get("type"), "Form")) {
                                schema.getEntities().stream().findFirst().ifPresent(mainEntity -> {
                                    List<Field> mainEntityFieldList = mainEntity.getType().getFields();
                                    childItem.computeIfAbsent("contents", k -> new ArrayList<HashMap<String, Object>>());

                                    FormTableInfo findTableInfo = metadataInfoItem.getFormTableInfo().getByCode(mainEntity.getCode());
                                    //childItem.get("contents")
                                    mainEntityFieldList.forEach(fieldItem -> {
                                        if (fieldItem instanceof SimpleField) {
                                            SimpleField simpleFieldItem = (SimpleField) fieldItem;
                                            String editorType = simpleFieldItem.getEditor().get$type();
                                            HashMap<String, Object> editorTypeParameter = CardTemplateEditorGenerator.generateWithEditorType(editorType);

                                            // 重新设置对应的控件id参数
                                            String strSplitId = fieldItem.getId().length() > 8 ? fieldItem.getId().substring(0, 8) : fieldItem.getId();
                                            String strGeneratedId = fieldItem.getBindingField() + "_" + strSplitId.replaceAll("-", "_") + "_" + RandomUtility.newGuid(4);
                                            editorTypeParameter.put("id", strGeneratedId);

                                            editorTypeParameter.put("title", fieldItem.getName());

                                            // require  editorTypeParameter.put("require",fieldItem.get)

                                            editorTypeParameter.put("appearance", "{\"class\":\"col-12 col-md-6 col-xl-3 col-el-2\"}");
                                            //readonly  editorTypeParameter.put("readonly",fieldItem.getre)
                                            editorTypeParameter.put("binding", new ComponentBinding() {
                                                {
                                                    this.setType("Form");
                                                    this.setPath(fieldItem.getBindingField());
                                                    this.setField(fieldItem.getId());
                                                    this.setFullPath(fieldItem.getPath());
                                                }
                                            });
                                            editorTypeParameter.put("path", fieldItem.getBindingPath());
                                            if (Objects.equals(editorTypeParameter.get("type"), "EnumField")) {
                                                //  editorTypeParameter.put("enumData",fieldItem.getType().)   设置对应的枚举数据
                                                editorTypeParameter.put("idField", "value");
                                                editorTypeParameter.put("textField", "name");
                                                // editorTypeParameter.put("maxSearchLength",fieldItem.getType().le)  获取列长度
                                            }

                                            if (Objects.equals(editorTypeParameter.get("type"), "NumericBox")) {
                                                //  editorTypeParameter.put("precision",fieldItem.getType().get$type()) 设置对应的精度
                                                if (Objects.equals(fieldItem.getType().get$type(), "BigNumericType")) {
                                                    editorTypeParameter.put("bigNumber", true);
                                                }
                                            }

                                            if (Objects.equals(editorTypeParameter.get("type"), "DateBox")) {
                                                editorTypeParameter.put("fieldType", fieldItem.getType().getName());
                                                editorTypeParameter.put("localization", false);
                                                editorTypeParameter.put("localizationType", fieldItem.getType().getName());
                                                if (Objects.equals(editorTypeParameter.get("fieldType"), "DateTime")) {
                                                    editorTypeParameter.put("showTime", true);
                                                    editorTypeParameter.put("dateFormat", "yyyy-MM-dd HH:mm:ss");
                                                    editorTypeParameter.put("returnFormat", "yyyy-MM-dd HH:mm:ss");
                                                }
                                            }


                                            if (findTableInfo != null) {
                                                Optional<FormFieldInfo> optionalFieldInfo = findTableInfo.getFieldInfoList().stream().filter(t -> t.getCode().equals(editorTypeParameter.get(fieldItem.getCode()))).findFirst();
                                                if (optionalFieldInfo.isPresent()) {
                                                    editorTypeParameter.put("visible", optionalFieldInfo.get().isShow());
                                                    editorTypeParameter.put("readonly", optionalFieldInfo.get().isReadOnly());
                                                    editorTypeParameter.put("require", optionalFieldInfo.get().isRequired());
                                                    if (optionalFieldInfo.get().isShow()) {
                                                        ((ArrayList<HashMap<String, Object>>) childItem.get("contents")).add(editorTypeParameter);
                                                    }
                                                }
                                            } else {
                                                ((ArrayList<HashMap<String, Object>>) childItem.get("contents")).add(editorTypeParameter);
                                            }
//                                            childItem.computeIfPresent("contents", (key, value) -> {
//                                                // 将编辑器 添加到contents节点下
//                                                ((ArrayList<HashMap<String, Object>>) value).add(editorTypeParameter);
//                                            });
                                        }
                                    });
                                });

                            }

                        });

                    });
                }

                // 更新对应的schemas
                String generatedFormDom = SerializeUtility.getInstance().serialize(formDOM);
                JsonNode contentNode = SerializeUtility.getInstance().toJsonNode(generatedFormDom);

                formMetadataContent.setContents(contentNode);

                formListMetadata.setContent(formMetadataContent);
                formListMetadata.setRefs(new ArrayList<>());
                // 保存对应的表单元数据
//                if (MetadataUtility.getInstance().isMetaDataExistsWithMetadataPathAndFileNameWithDesign(formListMetadata.getRelativePath(), formListMetadata.getHeader().getFileName())) {
//                    MetadataUtility.getInstance().deleteMetadataWithDesign(formListMetadata.getRelativePath(), formListMetadata.getHeader().getFileName());
//                }
                MetadataUtility.getInstance().saveMetadataWithDesign(formListMetadata);

                // 更新对应的页面流
                // 增加此操作的目的是为了在编译时可以将当前表单加入
                PageFlowMetadataUpdateService.getInstance().updatePageFlowMetadata(new MetadataEventArgs() {
                    {
                        this.setMetadata(formListMetadata);
                        this.setPath(formListMetadata.getRelativePath());
                    }
                });
            }
        }


        return resultMessage;
    }


    private void rescureHashMapWithContents(HashMap<String, Object> sourceHashMap, Consumer<HashMap<String, Object>> sourceItemConsumerAction) {
        if (sourceHashMap != null && !sourceHashMap.isEmpty()) {
            sourceItemConsumerAction.accept(sourceHashMap);

            if (sourceHashMap.get("contents") instanceof ArrayList) {
                ArrayList<HashMap<String, Object>> contentList = (ArrayList<HashMap<String, Object>>) sourceHashMap.get("contents");
                contentList.forEach(contentItem -> {
                    this.rescureHashMapWithContents(contentItem, sourceItemConsumerAction);
                });
            }
        }
    }


    /**
     * 入参校验
     *
     * @param parameter
     */
    private void createParameterValidate(DynamicCreateFormMetadataParameter parameter) {
        if (parameter == null) {
            throw new DynamicFormException("表单创建入参不能为空");
        }
        if (StringUtility.isNullOrEmpty(parameter.getProjectPath())) {
            throw new DynamicFormException("表单创建入参，工程路径不能为空");
        }
        if (StringUtility.isNullOrEmpty(parameter.getProjectCode())) {
            throw new DynamicFormException("表单创建入参，工程code不能为空");
        }


        if (StringUtility.isNullOrEmpty(parameter.getProjectNameSpace())) {
            throw new DynamicFormException("表单创建入参，工程命名空间不能为空");
        }

        if (parameter.getFormMetadataInfoList() == null || parameter.getFormMetadataInfoList().isEmpty()) {
            throw new DynamicFormException("表单创建入参，待创建的表单信息列表为空");
        }


    }

}
